package model

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/builder"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/core/stringx"
	"strings"
	"time"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

var (
	notificationFieldNames          = builder.RawFieldNames(&types.Notification{})
	notificationRows                = strings.Join(notificationFieldNames, ",")
	notificationRowsExpectAutoSet   = strings.Join(stringx.Remove(notificationFieldNames, "`id`", "`created_at`", "`updated_at`", "`deleted_at`"), ",")
	notificationRowsWithPlaceHolder = strings.Join(stringx.Remove(notificationFieldNames, "`id`", "`created_at`", "`updated_at`", "`deleted_at`"), "=?,") + "=?"
)

// NotificationModel 定义了管理通知的相关方法
type NotificationModel interface {
	Insert(data *types.Notification) (sql.Result, error)
	FindOne(id int64) (*types.Notification, error)
	FindByTypeAndID(id int64, notificationType string) (*types.Notification, error)
	FindAllEnabled() ([]types.Notification, error)
	Update(data *types.Notification) error
	Delete(id int64) error
}

// 默认的 NotificationModel 实现
type defaultNotificationModel struct {
	ctx   context.Context
	table string
	conn  sqlx.SqlConn
}

// NewNotificationModel 创建一个新的 defaultNotificationModel 实例
func NewNotificationModel(ctx context.Context, table string, conn sqlx.SqlConn) NotificationModel {
	return &defaultNotificationModel{
		ctx:   ctx,
		table: table,
		conn:  conn,
	}
}

// Insert 向数据库中插入一条新的通知记录
func (m *defaultNotificationModel) Insert(data *types.Notification) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?)", m.table, notificationRowsExpectAutoSet)
	logx.Infof("执行 SQL: %s, 参数: %v", query, data)
	result, err := m.conn.ExecCtx(m.ctx, query, data.Name, data.Type, data.Config)
	if err != nil {
		logx.Errorf("插入数据异常: %v", err)
	}
	return result, err
}

// FindOne 根据 ID 查找通知记录
func (m *defaultNotificationModel) FindOne(id int64) (*types.Notification, error) {
	query := fmt.Sprintf("select %s from %s where `id` = ? and deleted_at is null limit 1", notificationRows, m.table)
	logx.Infof("执行 SQL: %s, 参数: %d", query, id)
	var resp types.Notification
	err := m.conn.QueryRowCtx(m.ctx, &resp, query, id)
	if err != nil {
		if errors.Is(err, sqlc.ErrNotFound) {
			errMsg := fmt.Sprintf("数据库中未找到相关数据，ID: %d", id)
			logx.Errorf(errMsg)
			return nil, fmt.Errorf("%w: %s", sqlc.ErrNotFound, errMsg)
		}
		errMsg := fmt.Sprintf("查询数据库中数据异常: %v", err)
		logx.Errorf(errMsg)
		return nil, fmt.Errorf("query error: %w", err)
	}
	return &resp, nil
}

// FindByTypeAndID 根据 ID name 查找记录
func (m *defaultNotificationModel) FindByTypeAndID(id int64, notificationType string) (*types.Notification, error) {
	query := fmt.Sprintf("select %s from %s where `id` = ? and `type` = ? and deleted_at is null", notificationRows, m.table)
	logx.Infof("执行 SQL: %s, 参数: %d, %s", query, id, notificationType)
	var resp types.Notification
	err := m.conn.QueryRowCtx(m.ctx, &resp, query, id, notificationType)
	if err != nil {
		if errors.Is(err, sqlc.ErrNotFound) {
			errMsg := fmt.Sprintf("数据库中未找到相关数据，ID: %d, Type: %s", id, notificationType)
			logx.Errorf(errMsg)
			return nil, fmt.Errorf("%w: %s", sqlc.ErrNotFound, errMsg)
		}
		errMsg := fmt.Sprintf("查询数据库中数据异常: %v", err)
		logx.Errorf(errMsg)
		return nil, fmt.Errorf("query error: %w", err)
	}
	return &resp, nil
}

// FindAllEnabled 查找所有的通知记录
func (m *defaultNotificationModel) FindAllEnabled() ([]types.Notification, error) {
	query := fmt.Sprintf("select %s from %s where deleted_at is null", notificationRows, m.table)
	logx.Infof("执行 SQL: %s", query)
	var notifications []types.Notification
	err := m.conn.QueryRowsCtx(m.ctx, &notifications, query)
	if err != nil {
		logx.Errorf("查询数据库中所有数据异常: %v", err)
	}
	return notifications, err
}

// Update 更新数据库中的通知记录
func (m *defaultNotificationModel) Update(data *types.Notification) error {
	query := fmt.Sprintf("update %s set %s where `id` = ? and deleted_at is null", m.table, notificationRowsWithPlaceHolder)
	logx.Infof("执行 SQL: %s, 参数: %v", query, data)
	_, err := m.conn.ExecCtx(m.ctx, query, data.Name, data.Type, data.Config, data.ID)
	if err != nil {
		logx.Errorf("更新数据库中数据异常: %v", err)
	}
	return err
}

// Delete 根据 ID 逻辑删除通知记录
func (m *defaultNotificationModel) Delete(id int64) error {
	deletedAt := time.Now().Format("2006-01-02 15:04:05.000")

	query := fmt.Sprintf("update %s set `deleted_at` = ? where `id` = ?", m.table)
	logx.Infof("执行 SQL: %s, 参数: %d, %s", query, id, deletedAt)
	_, err := m.conn.ExecCtx(m.ctx, query, deletedAt, id)
	if err != nil {
		logx.Errorf("逻辑删除数据库中数据异常: %v", err)
	}
	return err
}
